var express = require('express');
var doSql = require('./db2.js')
var router = express.Router()
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });


router.get('/', function (req, res) {
    res.send('classify')
})
router.get('/list', function (req, res) {
    // var sql = 'select * from classify';
    // doSql.doSql(sql).then(data => {
    //     //  console.log(data);
    //     res.send(JSON.stringify(doSql.heal(data)))
    // })
    let { pages, pagesize, orderby = 'id', sort = 'desc', keyword } = req.query
    if (!pages) {
        pages = 0
    }
    if (!pagesize) {
        pagesize = 20
    }

    let sum = pages * pagesize
    var sql = `select * from classify`;
    var sqla = `select count(*) as total from classify`;

    if (keyword) {
        sql += ` where title like '${keyword}%'`
        sqla += ` where title like '${keyword}%'`
    }

    if (orderby) {
        sql += ` order by ${orderby} ${sort}`
    }

    sql += ` limit ${sum},${pagesize}`

    // console.log(sql);
    // console.log(sqla);

    var p1 = doSql.doSql(sql)
    var p2 = doSql.doSql(sqla)
    Promise.all([p1, p2]).then(data => {
        // console.log(data);
        res.send(JSON.stringify(doSql.heal(data[0], data[1].resultes[0].total)))
    })


})

router.post("/update", urlencodedParser, function (req, res) {
    var { id, name, type } = req.body;
    var sql = `update classify set name='${name}',type='${type}' where id=${id}`;
    doSql.doSql(sql).then(data => {
        res.send(doSql.hand(data));
    })
})

router.post("/save", urlencodedParser, function (req, res) {
    var { name, type } = req.body;
    var sql = `insert into classify(name,type)values ('${name}','${type}')`;
    doSql.doSql(sql).then(data => {
        res.send(doSql.hand(data));
    })
})

router.get("/delete", function (req, res) {
    var { id } = req.query;
    var sql = `delete from classify where id in(${id}) `;
    doSql.doSql(sql).then(data => {
        res.send(doSql.hand(data));
    })
})




// var server = app.listen(1111, function () {
//     var host = server.address().address
//     var port = server.address().port
//     console.log("应用实例，访问地址为 http://%s:%s", host, port)
// })
module.exports = router